package cn.antia.cep.page.action;

import cn.antia.cep.common.AntiaException;
import cn.antia.cep.db.hibernate.bean.User;
import cn.antia.cep.page.po.Prole;
import cn.antia.cep.busi.UserService;
import cn.antia.cwin.page.StrutsAction;

import java.util.List;

/**
 * User: xiao
 * Date: 2007-10-29
 * Time: 13:31:20
 * To do:
 */
public class UserRoleAction extends StrutsAction {
	private String action;
	private String userId;
	private UserService userService;

    public void setUserId(String userId) {
		this.userId = userId;
	}

	protected String action() throws AntiaException {
        if(action == null || action.trim().length() < 1){
            request.setAttribute("err_msg","请指定操作类型。");
            return "info";
        }
        action = action.trim();
        if(action.equals("queryUser")){
            return queryUser();
        }else if(action.equals("queryRole")){
            return queryRole();
        }else if(action.equals("save")){
            return save();
        }
        request.setAttribute("err_msg","Got a err operate type:" + action);
        return "info";
    }
	//保存
    private String save() {
        Integer uid = Integer.valueOf(userId);
        String addroles = request.getParameter("addroles");
        String redundant = request.getParameter("redundant");
        userService.updateUserRoles(uid, addroles, redundant);
        return queryRole();
    }
    //查询角色
    private String queryRole() {
        if(userId == null || userId.trim().length() < 1){
            request.setAttribute("ess_msg","Please appoint a user.");
            return "torole";
        }
        List<Prole> proles = userService.queryRolesByUser(Integer.parseInt(userId));
        request.setAttribute("proles",proles);
        request.setAttribute("userId",userId);
        return "torole";
    }

    private String queryUser() {
        String code = request.getParameter("code");
        String name = request.getParameter("name");
        if(code != null && code.trim().length() == 0){
            code = null;
        }
        if(name != null && name.trim().length() == 0){
            name = null;
        }
        if(code == null && name == null){
            request.setAttribute("err_msg","Please appoint query conditions.");
            return "info";
        }
        User user = new User();
        user.setModifyTime(null);
        user.setNickname(code);
        user.setName(name);
        List users = userService.find(user,false);
        request.setAttribute("users",users);
        if(users == null || users.size() < 1){
            request.setAttribute("message","Not found any users.");
            return "info";
        }
        return "touser";
    }


	public void setAction(String action) {
		this.action = action;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
